<template>
  <div
      class="login1"
      :style="{
      backgroundImage: 'url(' + require('@/assets/bg1.jpeg') + ')',
    }"
  >
    <Col :xs="22" :sm="20" :md="14" :lg="10" :xl="7">
      <Card>
        <div class="container">
          <img src="@/assets/logo-black.png" class="logo" />
          <div class="regist">健身会所管理系统</div>
          <Form
              ref="form"
              :model="form"
              :rules="rules"
              label-position="top"
              class="form"
          >
            <FormItem label="账号" prop="username">
              <Input
                  v-model="form.username"
                  prefix="ios-contact"
                  size="large"
                  clearable
                  placeholder="账号"
                  autocomplete="off"
              />
            </FormItem>
            <FormItem label="密码" prop="password">
              <Input
                  type="password"
                  v-model="form.password"
                  prefix="ios-lock"
                  size="large"
                  password
                  placeholder="请输入密码"
                  autocomplete="off"
              />
            </FormItem>
          </Form>
          <Button
              type="primary"
              size="large"
              :loading="loading"
              @click="submitLogin"
              long
              class="btn"
          >
            登录
          </Button>

        </div>
      </Card>
    </Col>
  </div>
</template>


<script>
import {
  login,
  userInfo,
  githubLogin,
  qqLogin,
  weiboLogin,
  wechatLogin,
  dingdingLogin,
  workwechatLogin,
  getJWT,
  sendLoginSms,
  smsLogin,
  initCaptcha,
  drawCodeImage,
  getOtherSet,
  getNotice,
} from "@/api/index";
import { validateMobile } from "@/libs/validate";
import Cookies from "js-cookie";
import Header from "@/views/main-components/header";
import Footer from "@/views/main-components/footer";
import LangSwitch from "@/views/main-components/lang-switch";
import RectLoading from "@/views/my-components/xboot/rect-loading";
import CountDownButton from "@/views/my-components/xboot/count-down-button";
import util from "@/libs/util.js";
export default {
  components: {
    CountDownButton,
    RectLoading,
    LangSwitch,
    Header,
    Footer,
  },
  data() {
    return {
      showMore: false,
      captchaId: "",
      captchaImg: "",
      loadingCaptcha: true,
      socialLogining: true,
      error: false,
      tabName: "username",
      saveLogin: true,
      getSms: "获取验证码",
      loading: false,
      sending: false,
      errorCode: "",
      form: {
        username: "",
        password: "",
        mobile: "",
        code: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "change",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "change",
          },
        ],
        imgCode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "change",
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "change",
          },
          {
            validator: validateMobile,
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    getCaptchaImg() {
      this.loadingCaptcha = true;
      initCaptcha().then((res) => {
        this.loadingCaptcha = false;
        if (res.success) {
          this.captchaId = res.result;
          this.captchaImg = drawCodeImage + this.captchaId;
        }
      });
    },
    sendSmsCode() {
      this.$refs.mobileLoginForm.validate((valid) => {
        if (valid) {
          this.sending = true;
          this.getSms = "发送中";
          sendLoginSms(this.form.mobile).then((res) => {
            this.getSms = "获取验证码";
            this.sending = false;
            if (res.success) {
              this.$Message.success("发送短信验证码成功");
              // 开始倒计时
              this.$refs.countDown.startCountDown();
            }
          });
        }
      });
    },
    afterLogin(res) {
      let accessToken = res.result;
      this.setStore("accessToken", accessToken);
      getOtherSet().then((res) => {
        if (res.result) {
          let domain = res.result.ssoDomain;
          Cookies.set("accessToken", accessToken, {
            domain: domain,
            expires: 7,
          });
        }
      });
      // 获取用户信息
      userInfo().then((res) => {
        if (res.success) {
          // 避免超过大小限制
          delete res.result.permissions;
          let roles = [];
          res.result.roles.forEach((e) => {
            roles.push(e.name);
          });
          delete res.result.roles;
          this.setStore("roles", roles);
          this.setStore("saveLogin", this.saveLogin);
          if (this.saveLogin) {
            // 保存7天
            Cookies.set("userInfo", JSON.stringify(res.result), {
              expires: 7,
            });
          } else {
            Cookies.set("userInfo", JSON.stringify(res.result));
          }
          this.setStore("userInfo", res.result);
          this.$store.commit("setUserInfo", res.result);
          // 加载菜单
          util.initRouter(this);
          // window.location.reload();
          this.$router.push({
            name: "home_index",
          });
        } else {
          this.loading = false;
        }
      });
    },
    submitLogin() {

      this.loading = true;
      login({
        username: this.form.username,
        password: this.form.password,
        captchaId: this.captchaId,
        saveLogin: this.saveLogin,
      }).then((res) => {
        if (res.success) {
          this.afterLogin(res);
        } else {
          this.loading = false;
          // this.getCaptchaImg();
        }
      });
    },
    toGithubLogin() {
      this.socialLogining = true;
      githubLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    toQQLogin() {
      this.socialLogining = true;
      qqLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    toWeiboLogin() {
      this.socialLogining = true;
      weiboLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    toWeixinLogin() {
      this.socialLogining = true;
      wechatLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    toDingdingLogin() {
      this.socialLogining = true;
      dingdingLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    toWorkwechatLogin() {
      this.socialLogining = true;
      workwechatLogin().then((res) => {
        if (res.success) {
          window.location.href = res.result;
        } else {
          this.socialLogining = false;
        }
      });
    },
    relatedLogin() {
      let q = this.$route.query;
      let error = q.error;
      if (error !== "" && error !== undefined) {
        this.$Message.error(error);
      }
      let related = q.related;
      let JWTKey = q.JWTKey;
      if (related && related == "1" && JWTKey) {
        getJWT({ JWTKey: JWTKey }).then((res) => {
          if (res.success) {
            this.socialLogining = true;
            let accessToken = res.result;
            this.setStore("accessToken", accessToken);
            getOtherSet().then((res) => {
              if (res.result) {
                let domain = res.result.ssoDomain;
                Cookies.set("accessToken", accessToken, {
                  domain: domain,
                  expires: 7,
                });
              }
            });
            // 获取用户信息
            userInfo().then((res) => {
              if (res.success) {
                // 避免超过大小限制
                delete res.result.permissions;
                let roles = [];
                res.result.roles.forEach((e) => {
                  roles.push(e.name);
                });
                delete res.result.roles;
                this.setStore("roles", roles);
                // 保存7天
                Cookies.set("userInfo", JSON.stringify(res.result), {
                  expires: 7,
                });
                this.setStore("userInfo", res.result);
                this.$store.commit("setUserInfo", res.result);
                // 加载菜单
                util.initRouter(this);
                this.$router.push({
                  name: "home_index",
                });
              } else {
                this.socialLogining = false;
                this.$Message.error("获取登录用户信息失败");
              }
            });
          } else {
            this.socialLogining = false;
            this.$Message.error("使用第三方账号登录失败");
          }
        });
      } else {
        this.socialLogining = false;
      }
    },
    handleDropDown(v) {
      if (v == "test") {
        this.test();
      } else if (v == "resetByMobile") {
        this.$router.push({
          name: "reset",
        });
      } else if (v == "resetByEmail") {
        this.$router.push({
          name: "reset",
          query: {
            type: "1",
          },
        });
      }
    },
    showNotice() {
      getNotice().then((res) => {
        if (res.success) {
          if (!res.result) {
            return;
          }
          let data = res.result;
          if (
              data.open &&
              (data.title || data.content) &&
              data.position == "LOGIN"
          ) {
            this.$Notice.info({
              title: data.title,
              desc: data.content,
              duration: data.duration,
            });
          }
        }
      });
    },
    test() {
      this.$Notice.info({
        title: "测试体验账号",
        desc: "账号：test或test2<br>密码：123456",
      });
    },
  },
  mounted() {
    this.showNotice();
    this.relatedLogin();
    // this.getCaptchaImg();
  },
};
</script>
<style lang="less">
.login1 {
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 4px;
    margin: 21px 24px;
    .logo {
      width: 50px;
      height: 50px;
      margin: 10px 0;
    }
    .regist {
      line-height: 1.8;
      margin-bottom: 30px;
      font-size: 19px;
    }
    .form {
      width: 100%;
      .ivu-form-item-label {
        color: #455560;
        font-weight: 500;
        line-height: 1.5;
      }
    }
    .btn {
      margin: 4px 0 20px 0;
    }
    .ivu-divider-inner-text {
      color: rgba(114, 132, 154, 0.7);
    }
    .other-login {
      display: flex;
      justify-content: center;
      align-items: center;
      .o-btn {
        line-height: 1.5;
        position: relative;
        display: flex;
        align-items: center;
        font-weight: 400;
        white-space: nowrap;
        text-align: center;
        border: 1px solid rgb(230, 235, 241);
        box-shadow: rgb(0 0 0 / 2%) 0px 2px 0px;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;
        user-select: none;
        touch-action: manipulation;
        height: 40px;
        padding: 8.5px 1.25rem;
        font-size: 14px;
        border-radius: 4px;
        color: rgb(69, 85, 96);
        background: rgb(255, 255, 255);
        &:hover {
          background-color: rgb(237, 237, 237);
          border-color: rgb(237, 237, 237);
        }
        img {
          width: 14px;
          margin-right: 8px;
        }
      }
    }
  }
}
</style>
